//
//  JKPhotoPickerCollectionViewController.swift
//  JKWeibo
//
//  Created by albert on 16/6/28.
//  Copyright © 2016年 albert. All rights reserved.
//  自定义选择照片的UICollectionViewController

import UIKit
import SVProgressHUD

private let reuseId = "photoPickerCell"

class JKPhotoPickerCollectionViewController: UICollectionViewController {

    /** 图片数组 */
    var images = [UIImage]()
    
    /** 选中图片后的回调 */
    var didSelectPicBlock: (() -> ())?
    
    /** 删除图片后的回调 */
    var didDeletePicBlock: (() -> ())?
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    // MARK: 数据源
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        // 最多9张
        return (images.count == 9) ? images.count : images.count + 1
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        // 1.获取cell
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseId, forIndexPath: indexPath) as! JKPhotoPickerCell
        cell.delegate = self
        
        // 2.设置数据
        cell.image = (indexPath.item >= images.count) ? nil : images[indexPath.item]
        
        // 3.返回
        return cell
    }
}

// MARK: - 自定义cell代理实现
extension JKPhotoPickerCollectionViewController: JKPhotoPickerCellDelegate{
    /** 点击添加照片按钮 */
    func photoPickerCellDidClickAddPhotoButton(photoPickerCell: JKPhotoPickerCell) {
        // 1.判断照片源是否可用
        guard UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) else {
            SVProgressHUD.showErrorWithStatus("照片源不可用")
            SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.Black)
            JKDispatchTool.after(JKTipDuration) { () -> Void in
                SVProgressHUD.dismiss()
            }
            return
        }
        
        // 2.创建照片选择控制器
        let photoPickerVc = UIImagePickerController()
        
        // 3.设置照片yuan
        photoPickerVc.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
        
        // 4.设置代理
        photoPickerVc.delegate = self
        
        // 5.弹出照片选择控制器
        presentViewController(photoPickerVc, animated: true, completion: nil)
    }
    
    /** 点击右上角删除按钮 */
    func photoPickerCellDidClickremovePicButton(photoPickerCell: JKPhotoPickerCell) {
        let indexPath = collectionView!.indexPathForCell(photoPickerCell)!
        images.removeAtIndex(indexPath.item)
        collectionView?.reloadData()
        
        if didDeletePicBlock != nil {
            didDeletePicBlock!()
        }
    }
}

// MARK: - 照片选择控制器的代理
extension JKPhotoPickerCollectionViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        // 1.获取选中的照片
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        
        // 2.退出照片选择控制器
        picker.dismissViewControllerAnimated(true, completion: nil)
        
        // 3.用collectionView显示图片
        // 3.0压缩图片（指定宽度，让图片按比例压缩）
        let newImage = drawPicture(image, width: 450)
        
        /** 使用这个方法虽然也可以压缩，但是运行内存还是很大
        let data = UIImageJPEGRepresentation(image, 0.1)!
        let img = UIImage(data: data)! */
        
        // 3.1将图片存放进数组中
        images.append(newImage)
        // 3.2刷新表格
        collectionView?.reloadData()
        
        if didSelectPicBlock != nil {
            didSelectPicBlock!()
        }
    }
    
    /** 画图 */
    private func drawPicture(image: UIImage, width: CGFloat) -> UIImage {
        
        // 0.计算图片尺寸
        let height = (image.size.height / image.size.width) * width
        
        // 1.开启图形上下文
        UIGraphicsBeginImageContext(CGSize(width: width, height: height))
        
        // 2.将图片画到上下文
        image.drawInRect(CGRect(x: 0, y: 0, width: width, height: height))
        
        // 3.获取新的图片
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        
        // 4.关闭上下文
        UIGraphicsEndImageContext()
        
        // 5.返回新的图片
        return newImage
    }
}

// MARK: - 定义自定义cell代理
@objc
protocol JKPhotoPickerCellDelegate: NSObjectProtocol {
    /** 点击添加照片按钮 */
    optional func photoPickerCellDidClickAddPhotoButton(photoPickerCell: JKPhotoPickerCell)
    
    /** 点击右上角删除按钮 */
    optional func photoPickerCellDidClickremovePicButton(photoPickerCell: JKPhotoPickerCell)
}

// MARK: - 自定义cell
class JKPhotoPickerCell: UICollectionViewCell {
    
    /** 添加照片按钮 */
    @IBOutlet weak var addPhotoButton: UIButton!
    
    /** 右上角移除图片按钮 */
    @IBOutlet weak var removePicButton: UIButton!
    
    /** 代理属性 */
    weak var delegate: JKPhotoPickerCellDelegate?
    
    /** 图片 */
    var image: UIImage? {
        didSet {
            if image == nil {
                addPhotoButton.setBackgroundImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
                addPhotoButton.setBackgroundImage(UIImage(named: "compose_pic_add_highlighted"), forState: UIControlState.Highlighted)
                
                addPhotoButton.userInteractionEnabled = true
                removePicButton.hidden = true
                
            }else {
                addPhotoButton.setBackgroundImage(image, forState: UIControlState.Normal)
                
                addPhotoButton.userInteractionEnabled = false
                removePicButton.hidden = false
            }
        }
    }
    
    /** 添加图片按钮点击 */
    @IBAction func addPhotoBtnClick(sender: UIButton) {
        if let tempDelegate = delegate {
            if tempDelegate.respondsToSelector("photoPickerCellDidClickAddPhotoButton:") {
                tempDelegate.photoPickerCellDidClickAddPhotoButton!(self)
            }
        }
    }
    
    /** 右上角的删除按钮点击 */
    @IBAction func removePicBtnClick(sender: UIButton) {
        if let tempDelegate = delegate {
            if tempDelegate.respondsToSelector("photoPickerCellDidClickremovePicButton:") {
                tempDelegate.photoPickerCellDidClickremovePicButton!(self)
            }
        }
    }
}

class JKPhotoPickerFlowLayout: UICollectionViewFlowLayout {
    override func prepareLayout() {
        super.prepareLayout()
        
        // 1.计算item尺寸
        let photoMargin: CGFloat = 5
        let borderMargin: CGFloat = 10
        let col: CGFloat = 3
        let wh = (JKScreenW - borderMargin * 2 - photoMargin * (col - 1)) / col
        itemSize = CGSize(width: wh, height: wh)
        
        // 设置其它
        minimumInteritemSpacing = photoMargin
        minimumLineSpacing = photoMargin
        
        // 2.设置内边距
        sectionInset = UIEdgeInsets(top: borderMargin, left: borderMargin, bottom: 0, right: borderMargin)
        
        // 3.设置collectionView
        collectionView?.alwaysBounceVertical = true
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.showsVerticalScrollIndicator = false
    }
}
